package com.sakura.probe.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sakura.probe.common.api.CommonResult;
import com.sakura.probe.common.util.HttpServletRequestUtil;
import com.sakura.probe.common.util.JwtTokenUtil;
import com.sakura.probe.common.util.MailUtil;
import com.sakura.probe.dto.ImageHolder;
import com.sakura.probe.nosql.redis.RedisKey;
import com.sakura.probe.nosql.redis.RedisService;
import com.sakura.probe.pojo.PersonInfo;
import com.sakura.probe.service.OssService;
import com.sakura.probe.service.PersonInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Api(tags = "PersonSetController",description = "用户相关信息的修改编辑")
@Controller
@RequestMapping("/personSet")
@RequiresRoles(logical = Logical.OR,value = {"0","1","2","3"})
public class PersonSetController {
    @Autowired
    private RedisService redisService;
    @Autowired
    private PersonInfoService personInfoService;
    @Autowired
    private OssService ossService;

    @ApiOperation("修改用户名、性别、生日、院校其中一个")
    @ResponseBody
    @PostMapping("/modify")
    public CommonResult modify(String type,String content,HttpServletRequest request){
        String token = request.getHeader("Token");
        if (content!=null&&type!=null&&!"".equals(content)&& !"".equals(type)&&null!=token&&!"".equals(token)){
            PersonInfo person = redisService.getPersonByToken(token);
            if(type.equals("username")){
                //需要修改用户名,先判断该用户名有没有被其他用户使用
                PersonInfo one = personInfoService.getOne(new QueryWrapper<PersonInfo>()
                        .eq("username", content));
                if (null!=one){
                    return CommonResult.failed("该用户名太受欢迎了,请换另一个");
                }
                person.setUsername(content);
            }else if (type.equals("gender")){
                //需要修改性别
                person.setGender(content);
            }else if (type.equals("birthday")){
                //需要修改生日
                person.setBirthday(content);
            }else {
                //需要修改院校
                person.setSchool(content);
            }
            boolean result = personInfoService.updateById(person);
            if (result){
                redisService.set(RedisKey.getPersonInfo()+person.getUserId(), JSONUtil.toJsonStr(person));
            }
            return result?CommonResult.success("modify success"):CommonResult.failed("modify fail");
        }else {
            return CommonResult.failed("Parameter is not complete");
        }

    }

    @ApiOperation("修改图片")
    @ResponseBody
    @PostMapping("/modifyImg")
    public CommonResult modifyImg(HttpServletRequest request,String oldImg){
        String token = request.getHeader("Token");
        //获取修改的头像输入流
        ImageHolder headImg = HttpServletRequestUtil.getMultipartFile(request, "headImg");
        if (headImg.getStateEnum().getState()>0){
            //调用方法进行图片的修改
            return ossService.addHeadImage(redisService.getPersonByToken(token), oldImg, headImg.getMultipartFile());
        }else {
            return CommonResult.failed(headImg.getStateEnum().getStateInfo());
        }
    }

    @ApiOperation("修改密码")
    @ResponseBody
    @PostMapping("/modifyPas")
    public CommonResult modifyPassword(String oldPas,String newPas,String token){
        //先判断原来的密码是否正确
        PersonInfo person = redisService.getPersonByToken(token);
        if (!person.getPassword().equals(SecureUtil.md5(oldPas))){
            return CommonResult.failed("原密码不正确");
        }
        person.setPassword(SecureUtil.md5(newPas));
        boolean result = personInfoService.updateById(person);
        if (result){
            redisService.set(RedisKey.getPersonInfo()+person.getUserId(),JSONUtil.toJsonStr(person));
        }
        return result?CommonResult.success("修改成功"):CommonResult.failed("修改失败");
    }

    @ApiOperation("发送验证码到指定邮箱中--")
    @ResponseBody
    @GetMapping("/sendMailCode")
    public CommonResult sendMailCode(String mail){
        //先判断该邮箱是否有被注册过
        PersonInfo person = personInfoService.getOne(new QueryWrapper<PersonInfo>()
                .eq("mail", mail));
        if (null==person){
            return CommonResult.failed("该邮箱已有人使用");
        }
        //发送验证码到指定邮箱
        String code = "";
        try {
            //发送邮箱并且返回生成的验证码
            code = MailUtil.sendMail(mail);
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
        //将验证码存入redis中并设置存活时间为5分钟
        redisService.set(mail,code,300);
        return CommonResult.success("已发送验证码到指定邮箱中");
    }


    @ApiOperation("通过邮箱和验证码进行绑定--")
    @ResponseBody
    @GetMapping("/bindMail")
    public CommonResult bindMail(String mail,String code,String token){
        //先判断验证码是否正确,从redis中获取正确的验证码
        String actualCode = redisService.get(mail);
        if (actualCode==null||!code.equals(actualCode)){
            return CommonResult.failed("验证码不正确或已超时失效");
        }
        PersonInfo condition = new PersonInfo();
        condition.setMail(mail);
        condition.setUserId(Long.valueOf(JwtTokenUtil.getUsernameFromToken(token)));
        boolean result = personInfoService.updateById(condition);
        return result?CommonResult.success("绑定成功"):CommonResult.failed("绑定失败");
    }

    @ApiOperation("更换手机号")
    @ResponseBody
    @GetMapping("/changePhone")
    public CommonResult changePhone(String phone,String code,HttpServletRequest request){
        String token = request.getHeader("Token");
        //从redis中获取正确的验证码
        String r_code = redisService.get(phone);
        if (r_code==null || !code.equals(r_code)){
            //验证码不正确或过期
            return CommonResult.failed("验证码不正确或已过期");
        }
        PersonInfo condition = new PersonInfo();
        condition.setPhone(phone);
        condition.setUserId(Long.valueOf(JwtTokenUtil.getUsernameFromToken(token)));
        return personInfoService.updateById(condition)?CommonResult.success("更换成功")
                :CommonResult.failed("更换失败");
    }


}
